#include <texture.h>
#include <vector>
#include <array>
#include <stb_declare.h>
#include <SDL.h>
#include <vec2.h>
#include <utility_math.h>
#include <framebuffer.h>
#include <window_manager.h>
#include <log.h>
#include <memory>
#include <debug.h>

void log(const SDL_Rect& rect) {
    printf("x: %d y: %d w: %d h: %d\n", rect.x, rect.y, rect.w, rect.h);
}

void testTexture() {
    CheckFunc(SDL_Init(SDL_INIT_EVERYTHING));

    int width = 1280, height = 720;
    WindowManager manager(width, height, "testTexture");
    Framebuffer buffer(width, height);

    Texture texture;
    texture.createTexture(R"(C:\GraphicsDev\software-renderer\res\cube\container.jpg)");

    Vec2f triangle[3] = {
        Vec2f{ (float)width / 2,  (float)height / 2 - 300 },
        Vec2f{ (float)width / 2 - 300,  (float)height / 2 + 200 },
        Vec2f{ (float)width / 2 + 300,  (float)height / 2 + 200 }
    };

    Vec2f triangleUV[3] = {
        Vec2f{ 0.5f, 0.0f },
        Vec2f{ 0.0f, 1.0f },
        Vec2f{ 1.0f, 1.0f }
    };

    bool isQuit = false;
    SDL_Event event[1];

    while (!isQuit) {
        while (SDL_PollEvent(event)) {
            if (event->type == SDL_QUIT) {
                isQuit = true;
            }
        }
        manager.newFrame();
        buffer.clear();
        Bound2i rect = AABBbox(triangle[0], triangle[1], triangle[2]);

        for (auto point : rect) {
            Vec2f target = point + Vec2f{0.5f, 0.5f};
            if (isInTriangle(triangle[0], triangle[1], triangle[2], target)) {
                auto [alpha, beta, gamma] = barycentric(triangle[0], triangle[1], triangle[2], target);
                Vec2f uv = alpha * triangleUV[0] + beta * triangleUV[1] + gamma * triangleUV[2];
                buffer.getPixelCurrentColor(point) = vector_cast<std::uint8_t>(texture.nearestSimple(uv.u, uv.v));
            }
        }
        manager.swap(buffer.getPixelColorPtr());
    }

    SDL_Quit();
}

int main(int, char**) {
    try {
        testTexture();
    } 
    catch (std::exception& ex) {
        printf("%s", ex.what());
    }
    return 0;
}